<template>
  <div class="app_main">
    <div class="search_box">
      <el-form :inline="true" size="mini" :model="searchForm" ref="searchForm">
        <search-form-box>
          <template slot="showSearch">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="searchForm.name" placeholder="请输入姓名" size="small"></el-input>
            </el-form-item>
            <el-form-item label="部门" prop="dep_ids">
              <TreeSelect :data="departmentList" :height="400" :popover-width="300" default-expand-all
                          :default-props="{children: 'children',label: 'name',}" node-key="id" :multiple="true"
                          :collapseTags="true" @change="selectDeptChange" :checkedKeys="searchForm.dep_ids"
                          :clearable="true"
              />
            </el-form-item>
            <el-form-item label="职务" prop="job">
              <el-input v-model="searchForm.job" placeholder="请输入职务" size="small"></el-input>
            </el-form-item>
            <el-form-item label="身份证" prop="id_no">
              <el-input v-model="searchForm.id_no" placeholder="请输入身份证" size="small"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="mobile">
              <el-input v-model="searchForm.mobile" placeholder="请输入联系方式" size="small"></el-input>
            </el-form-item>
          </template>
          <template slot="hideSearch">
            <el-row>
              <el-form-item label="是否入编" prop="be_regular">
                <el-select v-model="searchForm.be_regular" clearable placeholder="请选择" size="small">
                  <el-option label="是" :value="1"></el-option>
                  <el-option label="否" :value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="入编时间" prop="comp_fill_entry_date_min">
                <el-date-picker v-model="searchForm.comp_fill_entry_date_min" type="date"
                                placeholder="开始时间" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" size="small"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item>至</el-form-item>
              <el-form-item prop="comp_fill_entry_date_max">
                <el-date-picker v-model="searchForm.comp_fill_entry_date_max" type="date"
                                placeholder="结束时间" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" size="small"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="是否签订保密协议" prop="sign_confidentiality_agree">
                <el-select v-model="searchForm.sign_confidentiality_agree" clearable placeholder="请选择"
                           size="small"
                >
                  <el-option label="是" :value="1"></el-option>
                  <el-option label="否" :value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="合同签订时间" prop="contract_sign_at_min">
                <el-date-picker v-model="searchForm.contract_sign_at_min" type="date" placeholder="开始时间"
                                format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" size="small"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item>至</el-form-item>
              <el-form-item prop="contract_sign_at_max">
                <el-date-picker v-model="searchForm.contract_sign_at_max" type="date" placeholder="结束时间"
                                format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" size="small"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="参保公司" prop="social_security_dep_id">
                <el-select v-model="searchForm.social_security_dep_id" placeholder="请选择" size="small"
                           :clearable="true"
                >
                  <el-option v-for="item in companyArr" :key="item.id" :label="item.name"
                             :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="参保时间" prop="social_security_date_min">
                <el-date-picker v-model="searchForm.social_security_date_min" type="date"
                                placeholder="开始时间" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" size="small"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item>至</el-form-item>
              <el-form-item prop="social_security_date_max">
                <el-date-picker v-model="searchForm.social_security_date_max" type="date"
                                placeholder="结束时间" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" size="small"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="年限时间" prop="years_begin_min">
                <el-date-picker v-model="searchForm.years_begin_min" type="date" placeholder="开始时间"
                                format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" size="small"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item>至</el-form-item>
              <el-form-item prop="years_end_max">
                <el-date-picker v-model="searchForm.years_end_max" type="date" placeholder="结束时间"
                                format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" size="small"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="离职时间" prop="leave_date_min">
                <el-date-picker v-model="searchForm.leave_date_min" type="date" placeholder="开始时间"
                                format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" size="small"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item>至</el-form-item>
              <el-form-item prop="leave_date_max">
                <el-date-picker v-model="searchForm.leave_date_max" type="date" placeholder="结束时间"
                                format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" size="small"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
          </template>
          <template slot="searchBtn">
            <el-form-item>
              <el-button type="primary" @click="searchSubmit" size="small">查询</el-button>
              <el-button @click="resetForm('searchForm')" size="small">重置</el-button>
            </el-form-item>
          </template>
        </search-form-box>
      </el-form>
    </div>
    <div>
      <el-button size="mini" type="primary" :disabled="multipleSelection.length<=0" @click="exportData">导出员工信息
      </el-button>
    </div>
    <div class="dataTable">
      <el-tabs v-model="searchForm.type" type="card" @tab-click="handleClick">
        <el-tab-pane label="在职" name="1">
          <el-table :data="tableData" size="mini" border style="width: 100%" v-loading="tableLoading"
                    @selection-change="handleSelectionChange"
          >
            <el-table-column fixed="left" type="selection" width="55"></el-table-column>
            <el-table-column fixed="left" type="index" label="序号" width="50" header-align="center" align="center">
              <template slot-scope="scope">
                <span>{{ (searchForm.page - 1) * searchForm.page_size + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column fixed="left" prop="name" label="姓名" width="120" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="mobile" label="联系方式" width="150" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="id_no" label="身份证" width="180" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="departmen_list_name" label="部门（职务）" show-overflow-tooltip min-width="200"
                             header-align="center"
            ></el-table-column>
            <el-table-column label="角色" show-overflow-tooltip min-width="200" header-align="center">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.role_names" :key="index" class="names-tag" size="mini">
                  {{ item }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="comp_fill_probation_start" label="考察期开始时间" width="150" header-align="center"
                             align="center"
            ></el-table-column>
            <el-table-column prop="comp_fill_probation_end" label="考察期结束时间" width="150" header-align="center"
                             align="center"
            ></el-table-column>
            <el-table-column label="是否入编" width="80" header-align="center" align="center">
              <template slot-scope="scope">
                <el-tag size="mini" type="success" v-if="scope.row.be_regular == 1">是</el-tag>
                <el-tag size="mini" type="danger" v-else-if="scope.row.be_regular == 0">否</el-tag>
                <el-tag size="mini" type="warning" v-else>未知</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="contract_sign_at" label="合同时间" width="150" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="comp_fill_entry_date" label="入编时间" width="150" header-align="center"
                             align="center"
            ></el-table-column>
            <el-table-column prop="social_security_date" label="参保时间" width="150" header-align="center"
                             align="center"
            ></el-table-column>
            <el-table-column prop="social_security_dep_name" label="参保公司" width="150" header-align="center"
                             align="center"
            ></el-table-column>
            <el-table-column prop="years_begin" label="年限开始" width="150" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="years_end" label="年限结束" width="150" header-align="center" align="center">
            </el-table-column>
            <el-table-column label="是否签订保密协议" width="100" header-align="center" align="center">
              <template slot-scope="scope">
                <el-tag size="mini" type="success" v-if="scope.row.sign_confidentiality_agree == 1">签订</el-tag>
                <el-tag size="mini" type="danger" v-else-if="scope.row.sign_confidentiality_agree == 0">未签订
                </el-tag>
                <el-tag size="mini" type="warning" v-else>未知</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="leave_date" label="离职时间" width="150" header-align="center" align="center">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="350" align="center" header-align="center">
              <template slot-scope="scope">
                <el-button-group>
                  <el-button @click="look(scope.row)" size="mini" v-permission="'look_details'">查看
                  </el-button>
                  <el-button v-if="scope.row.be_regular == 0 && scope.row.leave_date === null" type="primary"
                             @click="regularApply(scope.row.id)" size="mini"
                             v-permission="'roster_entry_apply'" :disabled="!scope.row.regular_apply_id"
                  >入编申请
                  </el-button>
                  <el-button v-if="scope.row.be_regular == 1 && scope.row.leave_date === null" type="success"
                             @click="transPosition(scope.row.id)" size="mini"
                             v-permission="'roster_trans_position'"
                  >调岗申请
                  </el-button>
                  <el-button v-if="scope.row.leave_date === null" type="warning" @click="showSetRole(scope.row)"
                             size="mini"
                             v-permission="'roster_set_role'"
                  >配置角色
                  </el-button>
                  <el-button type="primary" size="mini" @click="showMobileDialog(scope.row)">所有手机号</el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="已离职" name="2">
          <el-table :data="tableData" size="mini" border style="width: 100%" v-loading="tableLoading"
                    @selection-change="handleSelectionChange"
          >
            <el-table-column fixed="left" type="selection" width="55"></el-table-column>
            <el-table-column fixed="left" type="index" label="序号" width="50" header-align="center" align="center">
              <template slot-scope="scope">
                <span>{{ (searchForm.page - 1) * searchForm.page_size + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column fixed="left" prop="name" label="姓名" width="120" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="mobile" label="联系方式" width="150" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="id_no" label="身份证" width="180" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="departmen_list_name" label="部门（职务）" show-overflow-tooltip min-width="200"
                             header-align="center"
            ></el-table-column>
            <el-table-column label="角色" show-overflow-tooltip min-width="200" header-align="center">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.role_names" :key="index" class="names-tag" size="mini">
                  {{ item }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="comp_fill_probation_start" label="考察期开始时间" width="150" header-align="center"
                             align="center"
            ></el-table-column>
            <el-table-column prop="comp_fill_probation_end" label="考察期结束时间" width="150" header-align="center"
                             align="center"
            ></el-table-column>
            <el-table-column label="是否入编" width="80" header-align="center" align="center">
              <template slot-scope="scope">
                <el-tag size="mini" type="success" v-if="scope.row.be_regular == 1">是</el-tag>
                <el-tag size="mini" type="danger" v-else-if="scope.row.be_regular == 0">否</el-tag>
                <el-tag size="mini" type="warning" v-else>未知</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="contract_sign_at" label="合同时间" width="150" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="comp_fill_entry_date" label="入编时间" width="150" header-align="center"
                             align="center"
            ></el-table-column>
            <el-table-column prop="social_security_date" label="参保时间" width="150" header-align="center"
                             align="center"
            ></el-table-column>
            <el-table-column prop="social_security_dep_name" label="参保公司" width="150" header-align="center"
                             align="center"
            ></el-table-column>
            <el-table-column prop="years_begin" label="年限开始" width="150" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="years_end" label="年限结束" width="150" header-align="center" align="center">
            </el-table-column>
            <el-table-column label="是否签订保密协议" width="100" header-align="center" align="center">
              <template slot-scope="scope">
                <el-tag size="mini" type="success" v-if="scope.row.sign_confidentiality_agree == 1">签订</el-tag>
                <el-tag size="mini" type="danger" v-else-if="scope.row.sign_confidentiality_agree == 0">未签订
                </el-tag>
                <el-tag size="mini" type="warning" v-else>未知</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="leave_date" label="离职时间" width="150" header-align="center" align="center">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="80" align="center" header-align="center">
              <template slot-scope="scope">
                <el-button @click="look(scope.row)" size="mini" v-permission="'look_details'">查看
                </el-button>
                <!--                <el-button v-if="scope.row.be_regular == 0 && scope.row.leave_date === null" type="primary"-->
                <!--                           @click="regularApply(scope.row.id)" size="mini"-->
                <!--                           v-permission="'roster_entry_apply'" :disabled="!scope.row.regular_apply_id"-->
                <!--                >入编申请-->
                <!--                </el-button>-->
                <!--                <el-button v-if="scope.row.be_regular == 1 && scope.row.leave_date === null" type="success"-->
                <!--                           @click="transPosition(scope.row.id)" size="mini"-->
                <!--                           v-permission="'roster_trans_position'"-->
                <!--                >调岗申请-->
                <!--                </el-button>-->
                <!--                <el-button v-if="scope.row.leave_date === null" type="warning" @click="showSetRole(scope.row)"-->
                <!--                           size="mini"-->
                <!--                           v-permission="'roster_set_role'"-->
                <!--                >配置角色-->
                <!--                </el-button>-->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="paging_box">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="searchForm.page" :page-sizes="[10, 20, 50, 100,200,400]"
                     :page-size.sync="searchForm.page_size" layout="total, sizes, prev, pager, next, jumper"
                     :total="total"
      >
      </el-pagination>

      <el-dialog :close-on-click-modal="false" title="配置角色" center :visible.sync="dialogCU" width="40%"
                 @close="resetForm('cuForm')"
      >
        <el-form ref="cuForm" v-loading="dialogCULoading" :rules="cuRules" :model="cuForm" label-width="120px"
                 center
        >
          <el-form-item label="角色" prop="role_ids">
            <el-col :span="20">
              <el-select v-model="cuForm.role_ids" filterable placeholder="请选择角色" style="width:100%"
                         multiple @visible-change="visibleChangeRole" @change="changeRole"
                         @remove-tag="removeRole"
              >
                <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"
                           :disabled="item.status==0 || item.hide==1"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span
                    style="float: right; color: #8492a6; font-size: 12px;margin-right: 30px;"
                  >首页：{{
                      item.index_page
                    }}</span>
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="用户首页" prop="index_role_id">
            <el-col :span="20">
              <el-select v-model="cuForm.index_role_id" filterable clearable placeholder="请选择用户首页"
                         style="width:100%" no-data-text="请先选择角色"
              >
                <el-option v-for="item in roleIndexPageList" :key="item.id" :label="item.index_page"
                           :value="item.id"
                >
                  <span style="float: left">{{ item.index_page }}</span>
                  <span
                    style="float: right; color: #8492a6; font-size: 12px;"
                  >属于：{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="小程序首页" prop="mini_index_role_id">
            <el-col :span="20">
              <el-select v-model="cuForm.mini_index_role_id" filterable clearable placeholder="请选择小程序首页"
                         style="width:100%" no-data-text="请先选择角色"
              >
                <el-option v-for="item in roleMiniIndexPageList" :key="item.id"
                           :label="item.mini_index_page" :value="item.id"
                >
                  <span style="float: left">{{ item.mini_index_page }}</span>
                  <span
                    style="float: right; color: #8492a6; font-size: 12px;"
                  >属于：{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
					<el-button @click.native="dialogCU=false">取 消</el-button>
					<el-button type="primary" @click.native="onSubmitSetRole()">确 定</el-button>
				</span>
      </el-dialog>

      <!--关联手机号弹框-->
      <el-dialog class="user_mobile_dialog" :title="userName+'的手机号'" :visible.sync="userMobileDialogVisible"
                 width="500px" center @close="closeMobileDialog"
      >
        <div style="margin-bottom: 10px">
          <el-button type="primary" size="mini" @click="addMobile" :disabled="userMobileTableLoading">增加</el-button>
        </div>
        <el-table v-loading="userMobileTableLoading" :data="userMobileTableData" stripe size="mini" border>
          <el-table-column label="序号" width="50" align="center">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="手机号" min-width="100" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.can_input">
                <el-form v-if="tmpRow" ref="mobileForm" :model="tmpRow" :rules="mobileFormRule" size="mini">
                  <el-form-item style="display: inline-block;width: 70%" prop="mobile">
                    <el-input v-model="tmpRow.mobile" placeholder="请输入手机号"></el-input>
                  </el-form-item>
                  <div style="display: inline-block;width: 30%">
                    <el-button size="mini" type="text" @click="saveOrEdit">保存</el-button>
                    <el-button size="mini" type="text" @click="cancelInput(scope.row,scope.$index)">取消</el-button>
                  </div>
                </el-form>
              </div>
              <div v-if="!scope.row.can_input" style="position: relative">
                <span>{{ scope.row.mobile }}</span>
                <el-button style="position: absolute;right: 10px" v-if="scope.row.can_update" type="text"
                           size="mini" @click="editRow(scope.row)"
                >修改
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button v-if="scope.row.can_update" type="danger" size="mini"
                         @click="remove(scope.row,scope.$index)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="userMobileDialogVisible = false">关 闭</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import TreeSelect from '@/components/TreeSelect'
import {
  addOrEdit,
  export_excel,
  list, queryUserMobile, removeMobile, verifyMobile as verifyMobileFunction
} from '@/api/personnel/org/roster'
import {
  list as getDepartmentList
} from '@/api/system/department.js'
import {
  get_company
} from '@/api/system/department'
import {
  role_list,
  set_role
} from '@/api/system/user'
import {
  Message
} from 'element-ui'
import {
  cloneDeep
} from 'lodash'
import SearchFormBox from '@/components/SearchFormBox'

const reg_mobile = /^1(3|4|5|6|7|8|9)\d{9}$/

export default {
  created() {
    this.getList()
    this.getDepartmentList()
    this.initCompany()
    this.getRoleList()
  },
  components: {
    TreeSelect,
    SearchFormBox
  },
  data() {
    var verifyMobile = (rule, value, relation_id, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      }
      if (!reg_mobile.test(value)) {
        return callback(new Error('请输入正确的手机号'))
      }
      verifyMobileFunction({
        relation_id: relation_id,
        mobile: value
      }).then(res => {
        if (res.data) {
          return callback()
        } else {
          return callback(new Error('手机号已经绑定了用户'))
        }
      }).catch(() => {
        return callback(new Error('程序异常，请联系管理员'))
      })
    }
    return {
      searchForm: {
        page: 1,
        page_size: 10,
        name: null, // 姓名
        dep_ids: [],// 部门ID集合
        job: null, // 职务
        id_no: null, // 身份证号
        mobile: null, //	手机号
        be_regular: null, //	是否入编
        contract_sign_at_min: null, //	合同签订时间最小值
        contract_sign_at_max: null, //	合同签订时间最大值
        comp_fill_entry_date_min: null, //	入编时间最小值
        comp_fill_entry_date_max: null, //	入编时间最大值
        years_begin_min: null, //	年限开始最小值
        years_begin_max: null, //	年限开始最大值
        years_end_min: null, //	年限结束最小值
        years_end_max: null, //	年限结束最大值
        social_security_date_min: null, //	参保时间最小值
        social_security_date_max: null, //	参保时间最大值
        social_security_dep_id: null, //	参保公司id
        sign_confidentiality_agree: null, //	保密协议签订
        leave_date_min: null, //	离职时间最小值
        leave_date_max: null, //	离职时间最大值
        type: '1'// 1:未离职 2:已离职
      },
      listParams: {
        page: 1,
        page_size: 10,
        name: null, // 姓名
        dep_ids: [],
        job: null, // 职务
        id_no: null, // 身份证号
        mobile: null, //	手机号
        be_regular: null, //	是否入编
        contract_sign_at_min: null, //	合同签订时间最小值
        contract_sign_at_max: null, //	合同签订时间最大值
        comp_fill_entry_date_min: null, //	入编时间最小值
        comp_fill_entry_date_max: null, //	入编时间最大值
        years_begin_min: null, //	年限开始最小值
        years_begin_max: null, //	年限开始最大值
        years_end_min: null, //	年限结束最小值
        years_end_max: null, //	年限结束最大值
        social_security_date_min: null, //	参保时间最小值
        social_security_date_max: null, //	参保时间最大值
        social_security_dep_id: null, //	参保公司id
        sign_confidentiality_agree: null, //	保密协议签订
        leave_date_min: null, //	离职时间最小值
        leave_date_max: null, //	离职时间最大值
        type: '1'// 1:未离职 2:已离职
      },
      total: null, // 数据总数
      departmentList: [], // 部门数组
      companyArr: [], // 公司数组
      // 表格数据
      tableData: [],
      tableLoading: false,
      cuForm: {
        id: null,
        role_ids: [],
        index_role_id: null,
        mini_index_role_id: null
      },
      cuRules: {
        role_ids: [{
          required: true,
          message: '请选择角色',
          trigger: 'change'
        }],
        index_role_id: [{
          required: true,
          message: '请选择用户首页',
          trigger: 'change'
        }]
      },
      dialogCU: false,
      dialogCULoading: false,
      roleMiniIndexPageList: [],
      roleIndexPageList: [],
      roleList: [],
      roles: {},
      multipleSelection: [],
      userMobileDialogVisible: false,
      userMobileTableData: [],
      tmpRow: null,
      mobileFormRule: {
        mobile: [
          {
            validator: (rule, value, callback) => {
              return verifyMobile(rule, value, this.tmpRow.relation_id, callback)
            },
            trigger: 'blur'
          }
        ]
      },
      userMobileTableLoading: false,
      userName: '',
      userId: null
    }
  },
  methods: {
    regularApply(roster_id) {
      this.$router.push({ name: 'probation_assess_for_roster', params: { id: null, roster_id: roster_id } })
    },
    transPosition(roster_id) {
      this.$router.push({ name: 'trans_position_for_roster', params: { id: null, roster_id: roster_id } })
    },
    // 搜索方法
    searchSubmit() {
      this.searchForm.page = 1
      this.listParams = cloneDeep(this.searchForm)
      this.getList()
    },
    // 重置表单
    resetForm(formName) {
      switch (formName) {
        case 'cuForm':
          this.$refs['cuForm'].clearValidate()
          this.cuForm = {
            id: null,
            role_ids: [],
            index_role_id: null,
            mini_index_role_id: null
          }
          break
        case 'searchForm':
          this.$refs['searchForm'].resetFields()
          this.listParams = cloneDeep(this.searchForm)
          this.$nextTick(() => {
            this.getList()
          })
          break
      }
    },
    // 查看
    look(row) {
      this.$router.push({
        name: 'details_page',
        params: {
          user_id: row.id
        }
      })
    },
    handleSizeChange(val) {
      this.listParams.page_size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listParams.page = val
      this.getList()
    },
    getList() {
      this.tableLoading = true
      list(this.listParams).then(
        res => {
          this.tableLoading = false
          // this.tableData = res.data.records
          this.tableData = res.data.records.map(item => {
            if (item.role_names) {
              item.role_names = item.role_names.split(',')
            } else {
              item.role_names = []
            }

            if (item.department_list) {
              item.departmen_list_name = item.department_list.map((item, index) => {
                return item.name + (item.job ? ('(' + item.job + ')') : '')
              }).join('、')
            }
            return item
          })
          this.total = res.data.total
        }
      )
    },
    // 部门选项改变的回调
    selectDeptChange(val) {
      this.searchForm.dep_ids = val || []
    },
    // 获取部门信息
    getDepartmentList() {
      return getDepartmentList().then(res => {
        this.departmentList = res.data
      })
    },
    // 初始化公司数据
    initCompany() {
      get_company().then(
        res => {
          this.companyArr = res.data
        }
      )
    },
    onSubmitSetRole() {
      // 表单校验
      this.$refs.cuForm.validate(valid => {
        // ~ 校验通过
        if (valid) {
          var obj = Object.assign({}, this.cuForm)
          // 显示loading
          this.dialogCULoading = true
          // ~~ 设置角色
          this.setRole(obj)
        } else {
          // ~ 不通过
          return false
        }
      })
    },
    // 配置角色
    setRole(obj) {
      // 小程序首页不进行保存
      obj.mini_index_role_id = null
      return set_role(obj)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            this.dialogCU = false
            this.getList()
          }
          this.dialogCULoading = false
        })
        .catch(() => {
          this.dialogCULoading = false
        })
    },
    visibleChangeRole(show) {
      if (!show) {
        this.setRoleIndexPageList()
      }
    },
    changeRole(e) {
      const that = this
      this.setRoleIndexPageList()
    },
    removeRole(e) {
      const that = this
      that.setRoleIndexPageList(false, 'cuForm', !that.roleIsHide(e), e)
    },
    // 获得角色待选项列表
    getRoleList() {
      return role_list()
        .then(res => {
          const roles = {}
          cloneDeep(res.data).forEach(item => {
            roles['_' + item.id] = item
          })
          this.roles = roles
          this.roleList = cloneDeep(res.data)
          this.roleSearchList = cloneDeep(res.data)
        })
    },
    // 配置角色弹出框
    showSetRole(row) {
      this.cuForm.id = row.user_id
      this.cuForm.role_ids = (row.role_ids ? (row.role_ids.split(',').map(item => parseInt(item))) : [])
      this.cuForm.index_role_id = row.index_role_id
      this.cuForm.mini_index_role_id = row.mini_index_role_id
      this.setRoleIndexPageList(true)
      this.dialogCU = true
      this.dialogCULoading = false
    },
    setRoleIndexPageList(first = false, form = 'cuForm', canRemove = true, removeId) {
      const that = this
      if (!first) {
        if (form === 'cuForm') {
          that.cuForm.index_role_id = null
          that.cuForm.mini_index_role_id = null
        }
        if (form === 'cuFormTwo') {
          that.cuFormTwo.index_role_id = null
          that.cuFormTwo.mini_index_role_id = null
        }
      }

      if (form === 'cuForm') {
        that.roleIndexPageList = []
        that.roleMiniIndexPageList = []
      }
      if (form === 'cuFormTwo') {
        that.roleIndexPageListTwo = []
        that.roleMiniIndexPageListTwo = []
      }

      // 重新初始化首页select
      if (form === 'cuForm') {
        if (!canRemove) {
          that.cuForm.role_ids.push(removeId)
        }
        if (that.cuForm.role_ids) {
          that.cuForm.role_ids.forEach(item => {
            const temp = cloneDeep(that.roles['_' + item] || {})
            if (temp) {
              that.roleIndexPageList.push(temp)
              that.roleMiniIndexPageList.push(temp)
            }
          })
        }
      }
      if (form === 'cuFormTwo') {
        if (!canRemove) {
          that.cuFormTwo.role_ids.push(removeId)
        }
        if (that.cuFormTwo.role_ids) {
          that.cuFormTwo.role_ids.forEach(item => {
            const temp = cloneDeep(that.roles['_' + item] || {})
            if (temp) {
              that.roleIndexPageListTwo.push(temp)
              that.roleMiniIndexPageListTwo.push(temp)
            }
          })
        }
      }
    },
    roleIsHide(role_id) {
      const that = this
      const isHide = (that.roles['_' + role_id].hide || 0) == 1
      if (isHide) Message.error('业务所需角色，不允许去除用户关联')
      return isHide
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => {
        return item.id
      }) || []
    },
    exportData() {
      const params = {
        ids: this.multipleSelection.join(',')
      }
      export_excel(params)
    },
    handleClick() {
      this.$refs.searchForm.resetFields()
      this.searchSubmit()
      this.multipleSelection = []
    },
    showMobileDialog(row) {
      this.userMobileDialogVisible = true
      this.userName = row.name
      this.userId = row.user_id
      this.getUserMobileById()
    },
    closeMobileDialog() {
      this.userName = ''
      this.userId = null
      this.userMobileTableData = []
      this.tmpRow = null
    },
    getUserMobileById() {
      this.userMobileTableLoading = true
      queryUserMobile({ user_id: this.userId }).then(res => {
        this.userMobileTableLoading = false
        this.userMobileTableData = res.data.map(item => {
          return Object.assign({ can_input: false }, item)
        })
      }).catch(() => {
        this.userMobileTableLoading = false
      })
    },
    addMobile() {
      if (this.tmpRow !== null) {
        this.$confirm('当前有未保存的数据，确认放弃编辑增加新的手机号？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.giveUpEdit()
          const obj = {
            user_id: this.userId,
            mobile: '',
            can_update: true,
            can_input: true,
            is_create: true,
            relation_id: -1
          }
          this.userMobileTableData.push(obj)
          this.tmpRow = cloneDeep(obj)
        }).catch(() => {

        })
      } else {
        const obj = {
          user_id: this.userId,
          mobile: '',
          can_update: true,
          can_input: true,
          is_create: true,
          relation_id: -1
        }
        this.userMobileTableData.push(obj)
        this.tmpRow = cloneDeep(obj)
      }
    },
    saveOrEdit() {
      this.$refs.mobileForm.validate(flag => {
        if (flag) {
          console.log(this.tmpRow)
          const loading = this.$loading({
            lock: true,
            text: '保存中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          addOrEdit({
            id: this.tmpRow.relation_id === -1 ? null : this.tmpRow.relation_id,
            mobile: this.tmpRow.mobile,
            user_id: this.tmpRow.user_id
          }).then(res => {
            this.$message.success('保存成功')
            this.getUserMobileById()
            this.tmpRow = null
            loading.close()
          }).catch(() => {
            loading.close()
          })
        }
      })
    },
    cancelInput(row, index) {
      if (row.is_create) {
        this.userMobileTableData.splice(index, 1)
      } else {
        row.can_input = false
      }
      this.tmpRow = null
    },
    remove(row, index) {
      if (row.is_create) {
        this.userMobileTableData.splice(index, 1)
      } else {
        this.$confirm('确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '提交中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          removeMobile({ relation_id: row.relation_id }).then(res => {
            if (res.data) {
              this.$message.success('删除成功')
              this.getUserMobileById()
            } else {
              this.$message.error('删除失败')
            }
            loading.close()
          }).catch(() => {
            loading.close()
          })
        }).catch(() => {

        })
      }
    },
    editRow(row) {
      if (this.tmpRow !== null) {
        this.$confirm('当前有未保存的数据，确认放弃编辑，编辑新的手机号？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.giveUpEdit()
          this.tmpRow = cloneDeep(row)
          row.can_input = true
        }).catch(() => {

        })
      } else {
        this.tmpRow = cloneDeep(row)
        row.can_input = true
      }
    },
    giveUpEdit() {
      for (let i = 0; i < this.userMobileTableData.length; i++) {
        const item = this.userMobileTableData[i]
        if (item.can_input) {
          if (item.is_create) {
            this.userMobileTableData.splice(i, 1)
          } else {
            item.can_input = false
          }
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.app_main {
  padding: 0 10px;
}

.search_box {
  margin-top: 10px;
}

.dataTable {
  margin-top: 20px;
}

.paging_box {
  margin-top: 20px;
}

/deep/ .el-range-separator {
  width: 20px !important;
}

/deep/ .el-form-item {
  margin-bottom: 10px;
}

.names-tag {
  box-sizing: border-box;
  margin: 3px;
}

/deep/ .el-dialog__body .el-form-item {
  margin-bottom: 22px;
}

/deep/ .user_mobile_dialog .el-form-item {
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>
